
package com.zcp.notepad;

import com.zcp.notepad.NotePad.Notes;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class FileDocumentEditor extends Activity {
    EditText editor;

    Button btnDone;

    String mFilePath;

    RadioGroup group;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.file_document_editor);
        Intent intent = getIntent();
        btnDone = (Button) findViewById(R.id.noteDone);
        long now = System.currentTimeMillis();
        String date = Util.getDateStr(this, now) + " " + Util.getTimeStr(this, now);
        ((TextView) findViewById(R.id.noteTitle)).setText(date);
        String text = "";
        if ("file".equals(intent.getScheme())) {
            mFilePath = intent.getData().getPath();
            try {
                text = getFileContent(mFilePath);
            } catch (Exception e) {
                e.printStackTrace();
                // 文件过大时无法打开，直接关闭
            }

            btnDone.setEnabled(true);
        } 

        editor = (EditText) findViewById(R.id.note);
        editor.setText(text);
        btnDone.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                LayoutInflater inflater = FileDocumentEditor.this.getLayoutInflater();
                View view = inflater.inflate(R.layout.file_save_dialog, null);
                group = (RadioGroup) view.findViewById(R.id.saveWay);
                new AlertDialog.Builder(FileDocumentEditor.this)
                        .setView(view)
                        .setTitle(R.string.save_way)
                        .setPositiveButton(R.string.alert_dialog_ok,
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int whichButton) {
                                        int checkId = group.getCheckedRadioButtonId();
                                        switch (checkId) {
                                            case R.id.sateToFile:
                                                saveToFile(mFilePath);
                                                break;
                                            case R.id.sateToNote:
                                                saveToNote();
                                                break;
                                        }
                                        dialog.dismiss();
                                        finish();
                                    }
                                })
                        .setNegativeButton(R.string.alert_dialog_cancel,
                                new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                }).show();
            }
        });
        findViewById(R.id.noteCancel).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void saveToFile(String path) {
        File targetFile = new File(path);
        BufferedWriter writer = null;
        try {
            writer = new BufferedWriter(new FileWriter(targetFile));

            writer.write(editor.getText().toString());

            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (writer != null)
                    writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }

    private void saveToNote() {
        ContentValues values = new ContentValues();
        String text = editor.getText().toString();
        if (TextUtils.isEmpty(text.trim())) {
            showText(R.string.save_cannot_empty);
            return;
        }
        values.put(Notes.NOTE, text);
        values.put(Notes.TYPE, Notes.Color.ORANGE);
        values.put(Notes.TITLE, Util.makeTitle(text));
        getContentResolver().insert(Notes.CONTENT_URI, values);
        showText(R.string.save_success);
    }

    private String getFileContent(String path) throws Exception {
        StringBuilder sb = new StringBuilder();
        InputStream in = null;
        File file = new File(path);

        BufferedReader reader = null;
        String buff = "";
        try {
            if (file.length() > 200000) {
                Toast.makeText(this, R.string.file_too_large, Toast.LENGTH_SHORT).show();
                finish();
                return null;
            }
            in = new BufferedInputStream(new FileInputStream(file));
            String encoding = Util.getEncoding(in, 1000);
            reader = new BufferedReader(new InputStreamReader(in, encoding));
            while ((buff = reader.readLine()) != null) {
                sb.append(buff);
                sb.append("\n");
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null)
                reader.close();
            if (in != null)
                in.close();
        }

        return sb.toString();
    }

    private void showText(int StringId) {
        Toast.makeText(this, getString(StringId), Toast.LENGTH_SHORT).show();
    }

}
